package com.funny.springcloud.controller;

import com.funny.springcloud.entities.Payment;
import com.funny.springcloud.service.PaymentService;
import com.funny.springcloud.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/payment/add")
    public R<Integer> addPayment(@RequestBody Payment payment) {
        int result = paymentService.add(payment);
        if (result > 0) {
            log.info("插入数据成功");
            return new R(200, "插入数据成功 serverPort:" + serverPort, result);
        }
        log.error("插入数据失败");
        return new R(500, "插入数据失败 serverPort:" + serverPort, null);
    }

    @GetMapping("/payment/get/{id}")
    public R<Payment> getPayment(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null) {
            log.info("获取数据成功");
            return new R(200, "获取数据成功 serverPort:" + serverPort, payment);
        }
        log.info("没有对应的记录");

        return new R(404, "没有对应的记录serverPort:" + serverPort, null);
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service:" + service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("instance:" + instance.getServiceId() + "\t" +
                    instance.getHost() + "\t" +
                    instance.getPort() + "\t" +
                    instance.getUri());
        }
        return discoveryClient;
    }

    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout() {
        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
        return serverPort;
    }

    @GetMapping(value="/payment/zipkin")
    public String paymentZipkin() {
        return "hello,i am paymentZipkin server fallback,O(∩_∩)O哈哈~";
    }
}
